const _ = require("lodash");
const moment = require("moment");

const models = require(__base + '/models');
const errcode = require(__util + "/errcode");
const ct = require(__util + "/catch"); // 路由错误捕获(不使用则不会捕获异常错误)

module.exports = ct(async (req, res) => {
  let { endpoint, limit, offset, sort } = req.body

  limit = limit || 20  // 限制读取的数据最大量
  offset = offset || 0  // 设置从第几条数据开始读取
  sort = sort ? ((_.keys(sort).length > 0) ? sort : { "status": 'DESC' }) : { "status": 'DESC' } // 设置默认排序条件

  // 查询条件
  const where = {}
  // 模糊查询endpoint
  if (endpoint) {
    where.endpoint = {
      $regexp: endpoint
    }
  }

  // 排序条件
  const order = []
  for (let key in sort) {
    order.push([`${key}`, `${sort[key]}`])
  }

  const { count, rows } = await models.Eosendpoint.findAndCount({
    where: where,
    order: order,
    offset: offset,
    limit: limit,
    attributes: ['id', 'endpoint', 'status', 'testTotal', 'successTotal', 'failTotal', 'updatedAt']
  })
  rows.map(el => {
    const val = el.get({ plain: true })
    val.updatedAt = moment(val.updatedAt).format("YYYY-MM-DD HH:mm:ssss")
    return val
  })

  return res.json(
    errcode.SUCCESS({
      count: count,
      rows: rows
    })
  );
});